﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ZG_member.BLL;
using System.Configuration;

namespace ZG_member
{
    public partial class ConsumptionBill : Form
    {
        MainForm mainform;
        public ConsumptionBill(MainForm main)
        {
            InitializeComponent();
            mainform = main;
            skinEngine1.SkinFile = Application.StartupPath + ConfigurationManager.AppSettings["Skin"]; 
        }


        decimal pageSize=18;
        int pageNum=1;
        int pages;
        decimal ss;
        string strWhere="";
        int sousuo = 0;
        private void ConsumptionBill_Load(object sender, EventArgs e)
        {
            this.label3.ForeColor = Color.Gray;
            this.Opacity = 0;
            this.timer1.Start();
            operatorInfo opInfo = new operatorInfo();
            DataTable dataTable = opInfo.GetList("").Tables[0];
            if (dataTable.Rows.Count > 0)
            {
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    if (!CbxAdmin.Items.Contains(dataTable.Rows[i]["username"].ToString()))
                    {
                        CbxAdmin.Items.Add(dataTable.Rows[i]["username"].ToString());
                    }
                }
            }
            CurrYe();
            CbxAdmin.SelectedIndex = 0;
            DgvShow();
        }

        public void CurrYe()
        {
            wasteBook wast=new wasteBook();
            ZG_member.Model.wasteBook wastModel = new ZG_member.Model.wasteBook();
            decimal count= wast.GetList("").Tables[0].Rows.Count;
             string s=  (count / pageSize).ToString();
             ss= Math.Floor(decimal.Parse(s));
             if (decimal.Parse(s) > ss)
             {
                 ss++;
             }
            label2.Text = pageNum + "/"+ss;
        }
   


        private void btnInquiry_Click(object sender, EventArgs e)
        {
            sousuo = 1;
            Inquiry();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            ExportExcel(" ", DgvConsumptionBill);
        }

        /// <summary>
        /// Dgv连接数据库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void DgvShow() 
        {
            wasteBook wastebook = new wasteBook();
            DataTable dt = wastebook.Pagination(Convert.ToInt32(pageSize), pageNum,"").Tables[0];
            DgvConsumptionBill.DataSource = dt;
            DgvConsumptionBill.AllowUserToAddRows = false;
            consumeSolution consume = new consumeSolution();
            Model.consumeSolution consumeMod = new Model.consumeSolution();
            if (DgvConsumptionBill.Rows.Count > 0)
            {
                for (int i = 0; i < DgvConsumptionBill.Rows.Count; i++)
                {
                    if (DgvConsumptionBill.Rows[i].Cells["consumeType"].Value.ToString() != "")
                    {
                        consumeMod = consume.GetModel(int.Parse(DgvConsumptionBill.Rows[i].Cells["consumeType"].Value.ToString()));
                        DgvConsumptionBill.Rows[i].Cells["CardType"].Value = consumeMod.solutionName;
                    }
                    if (DgvConsumptionBill.Rows[i].Cells["Discount"].Value.ToString() != "")
                    {
                        DgvConsumptionBill.Rows[i].Cells["DiscountNew"].Value = DgvConsumptionBill.Rows[i].Cells["Discount"].Value+"%";
                    }
                }
            }
        
        }
        /// <summary>
        /// 按条件查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 
        public void Inquiry() 
        {
            StringBuilder stringBuilder = new StringBuilder();
            if (CbxAdmin.Text != "所有操作员")
            {
                stringBuilder.Append("operatorId='" + CbxAdmin.Text.Trim() + "'");
                stringBuilder.Append("and ");
            }
            if (!string.IsNullOrEmpty(TxtConsumer.Text))
            {
                stringBuilder.Append("memberCardId='" + TxtConsumer.Text.Trim() + "'");
                stringBuilder.Append("and ");
            }
            if (DateTime.Parse(DtpDate.Text) <= DateTime.Parse(DtpDate1.Text))
            {
                stringBuilder.Append("date between '" + DateTime.Parse(DtpDate.Text) + "'and'" + DateTime.Parse(DtpDate1.Text) + "'");
                stringBuilder.Append("and ");
            }
            else
            {
                stringBuilder.Append("date=''");
                stringBuilder.Append("and ");
                MessageBox.Show("日期错误");
            }
            string strBuilder = stringBuilder.ToString();

            if (strBuilder.Substring(strBuilder.Length - 4, 4) == "and ")
            {
                strBuilder = strBuilder.Substring(0, strBuilder.Length - 4);
            }
            strWhere = strBuilder;
            wasteBook wastebook = new wasteBook();
            DataTable dt = wastebook.Pagination(Convert.ToInt32(pageSize),pageNum,strBuilder).Tables[0];
            DgvConsumptionBill.DataSource = dt;
            int count = wastebook.GetList(strBuilder).Tables[0].Rows.Count;
            decimal xiaoshu = count / pageSize;
            int zhengshu = Convert.ToInt32(Math.Floor(xiaoshu));
            if (xiaoshu > zhengshu)
            {
                zhengshu++;
            }
            pageNum = 1;
            ss = zhengshu;
            label2.Text = pageNum + "/" + zhengshu;
            DgvConsumptionBill.AllowUserToAddRows = false;

            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (DgvConsumptionBill.Rows[i].Cells["consumeType"].Value.ToString() != "")
                    {
                        consumeSolution consume = new consumeSolution();
                        Model.consumeSolution consumeMod = new Model.consumeSolution();
                        consumeMod = consume.GetModel(int.Parse(DgvConsumptionBill.Rows[i].Cells["consumeType"].Value.ToString()));
                        DgvConsumptionBill.Rows[i].Cells["CardType"].Value = consumeMod.solutionName;
                    }
                }
            }
           
        
        }




        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="Dgv"></param>
        public void ExportExcel(string fileName, DataGridView myDGV)
        {
            string saveFileName = "";
            //bool fileSaved = false;
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.DefaultExt = "xls";
            saveDialog.Filter = "Excel文件|*.xls";
            saveDialog.FileName = fileName;
            saveDialog.ShowDialog();
            saveFileName = saveDialog.FileName;
            if (saveFileName.IndexOf(":") < 0) return; //被点了取消 
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            if (xlApp == null)
            {
                MessageBox.Show("无法创建Excel对象，可能您的机子未安装Office.Excel组件");
                return;
            }
            Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1 
            int colIndex = 0;
            //写入标题
            for (int i = 0; i < myDGV.ColumnCount; i++)
            {
                if (myDGV.Columns[i].Visible)
                {
                    colIndex++;
                    worksheet.Cells[1, colIndex] = myDGV.Columns[i].HeaderText;
                    //  worksheet.Cells[1, i] = myDGV.Columns[i].HeaderText;
                }
            }
            //写入数值
            for (int r = 0; r < myDGV.Rows.Count; r++)
            {
                colIndex = 0;
                for (int i = 0; i < myDGV.ColumnCount; i++)
                {
                    if (myDGV.Columns[i].Visible)
                    {
                        colIndex++;
                        worksheet.Cells[r + 2, colIndex] = myDGV.Rows[r].Cells[i].Value;
                    }
                }
                System.Windows.Forms.Application.DoEvents();
            }
            worksheet.Columns.EntireColumn.AutoFit();//列宽自适应

            if (saveFileName != "")
            {
                try
                {
                    workbook.Saved = true;
                    workbook.SaveCopyAs(saveFileName);
                    //fileSaved = true;
                }
                catch (Exception ex)
                {
                    //fileSaved = false;
                    MessageBox.Show("导出文件时出错,文件可能正被打开！/n" + ex.Message);
                }

            }
            xlApp.Quit();
            GC.Collect();//强行销毁 
            // if (fileSaved && System.IO.File.Exists(saveFileName)) System.Diagnostics.Process.Start(saveFileName); //打开EXCEL

            MessageBox.Show(fileName + "导出成功", "系统提示", MessageBoxButtons.OK);
        }


        int flag = 0;
        private void ConsumptionBill_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (flag == 0)
            {
                e.Cancel = true;
                flag = 1;
                this.timer2.Start();
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //timer开启
            this.Left += 2;
            this.Opacity += 0.1;
            if (Opacity == 1)
            {
                this.timer1.Stop();

            }
        }

        private void timer2_Tick_1(object sender, EventArgs e)
        {
            //timer关闭
            this.Top = this.Top + 10;
            this.Opacity = this.Opacity - 0.06;
            if (Opacity <= 0)
            {
                this.timer2.Stop();
                this.Close();
            }
        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (sousuo == 0)
            {
                if (pageNum == ss)
                {
                    MessageBox.Show("已是最终页");
                }
                else
                {
                    pageNum++;
                }
                DgvShow();
                this.label2.Text = pageNum + "/" + ss;
            }
            else
            {
                if (pageNum != ss)
                {
                    pageNum++;
                    wasteBook waste = new wasteBook();
                    DataTable ds = waste.Pagination(Convert.ToInt32(pageSize), pageNum, strWhere).Tables[0];
                    consumeSolution consume = new consumeSolution();
                    Model.consumeSolution consumeMod = new Model.consumeSolution();
                    DgvConsumptionBill.DataSource = ds;
                    if (DgvConsumptionBill.Rows.Count > 0)
                    {
                        for (int i = 0; i < DgvConsumptionBill.Rows.Count; i++)
                        {
                            if (DgvConsumptionBill.Rows[i].Cells["consumeType"].Value.ToString() != "")
                            {
                                consumeMod = consume.GetModel(int.Parse(DgvConsumptionBill.Rows[i].Cells["consumeType"].Value.ToString()));
                                DgvConsumptionBill.Rows[i].Cells["CardType"].Value = consumeMod.solutionName;
                            }
                            if (DgvConsumptionBill.Rows[i].Cells["Discount"].Value.ToString() != "")
                            {
                                DgvConsumptionBill.Rows[i].Cells["DiscountNew"].Value = DgvConsumptionBill.Rows[i].Cells["Discount"].Value + "%";
                            }
                        }
                    }
                    this.label2.Text = pageNum + "/" + ss;
                }
                else
                {
                    MessageBox.Show("已是最终页");
                }
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (sousuo == 0)
            {
                pageNum--;
                if (pageNum < 1)
                {
                    pageNum = 1;
                    MessageBox.Show("已是首页");
                    return;
                }
                this.label2.Text = pageNum + "/" + ss;
                DgvShow();
            }
            else
            {
                if (pageNum > 1)
                {
                    pageNum--;
                    wasteBook waste=new wasteBook();
                    DataTable dt = waste.Pagination(Convert.ToInt32(pageSize), pageNum, strWhere).Tables[0];
                    DgvConsumptionBill.DataSource = dt;
                    this.label2.Text = pageNum + "/" + ss;
                    consumeSolution consume = new consumeSolution();
                    Model.consumeSolution consumeMod = new Model.consumeSolution();
   
                    if (DgvConsumptionBill.Rows.Count > 0)
                    {
                        for (int i = 0; i < DgvConsumptionBill.Rows.Count; i++)
                        {
                            if (DgvConsumptionBill.Rows[i].Cells["consumeType"].Value.ToString() != "")
                            {
                                consumeMod = consume.GetModel(int.Parse(DgvConsumptionBill.Rows[i].Cells["consumeType"].Value.ToString()));
                                DgvConsumptionBill.Rows[i].Cells["CardType"].Value = consumeMod.solutionName;
                            }
                            if (DgvConsumptionBill.Rows[i].Cells["Discount"].Value.ToString() != "")
                            {
                                DgvConsumptionBill.Rows[i].Cells["DiscountNew"].Value = DgvConsumptionBill.Rows[i].Cells["Discount"].Value + "%";
                            }
                        }
                    }
                }
                else
                {
                    MessageBox.Show("已是第一页");
                }
            }  
        }

        private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                if (sousuo == 0)
                {
                    wasteBook waste = new wasteBook();
                    ZG_member.Model.wasteBook wasteModel = new ZG_member.Model.wasteBook();
                    DataTable dt = waste.Pagination(Convert.ToInt32(pageSize), Convert.ToInt32(textBox1.Text), "").Tables[0];
                    if (dt.Rows.Count != 0)
                    {
                        DgvConsumptionBill.DataSource = dt;
                        DgvConsumptionBill.AllowUserToAddRows = false;
                        pageNum = Convert.ToInt32(this.textBox1.Text);
                        this.label2.Text = pageNum + "/" + ss;
                        operatorInfo opInfo = new operatorInfo();

                        consumeSolution consume = new consumeSolution();
                        Model.consumeSolution consumeMod = new Model.consumeSolution();
                        if (DgvConsumptionBill.Rows.Count > 0)
                        {
                            for (int i = 0; i < DgvConsumptionBill.Rows.Count; i++)
                            {
                                if (DgvConsumptionBill.Rows[i].Cells["consumeType"].Value.ToString() != "")
                                {
                                    consumeMod = consume.GetModel(int.Parse(DgvConsumptionBill.Rows[i].Cells["consumeType"].Value.ToString()));
                                    DgvConsumptionBill.Rows[i].Cells["CardType"].Value = consumeMod.solutionName;
                                }
                                if (DgvConsumptionBill.Rows[i].Cells["Discount"].Value.ToString() != "")
                                {
                                    DgvConsumptionBill.Rows[i].Cells["DiscountNew"].Value = DgvConsumptionBill.Rows[i].Cells["Discount"].Value + "%";
                                }
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("已超出最大页数");
                        return;
                    }
                }
                else
                {
                    int yeshu =Convert.ToInt32(this.textBox1.Text);
                    wasteBook wasteTwo = new wasteBook();
                   DataTable dt=  wasteTwo.Pagination(Convert.ToInt32(pageSize), yeshu, strWhere).Tables[0];
                   if (dt.Rows.Count > 0)
                   {
                       pageNum = yeshu;
                       consumeSolution consume = new consumeSolution();
                       Model.consumeSolution consumeMod = new Model.consumeSolution();
                       DgvConsumptionBill.DataSource = dt;
                       if (DgvConsumptionBill.Rows.Count > 0)
                       {
                           for (int i = 0; i < DgvConsumptionBill.Rows.Count; i++)
                           {
                               if (DgvConsumptionBill.Rows[i].Cells["consumeType"].Value.ToString() != "")
                               {
                                   consumeMod = consume.GetModel(int.Parse(DgvConsumptionBill.Rows[i].Cells["consumeType"].Value.ToString()));
                                   DgvConsumptionBill.Rows[i].Cells["CardType"].Value = consumeMod.solutionName;
                               }
                               if (DgvConsumptionBill.Rows[i].Cells["Discount"].Value.ToString() != "")
                               {
                                   DgvConsumptionBill.Rows[i].Cells["DiscountNew"].Value = DgvConsumptionBill.Rows[i].Cells["Discount"].Value + "%";
                               }
                           }
                       }
                       this.label2.Text = pageNum + "/" + ss;
                   }
                   else
                   {
                       MessageBox.Show("输入的页数超过最大范围");
                   }

                }
            }
            catch (Exception)
            {

                MessageBox.Show("请输入合法内容");
            }
           
         }
        private void DgvConsumptionBill_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            consumeSolution consume = new consumeSolution();
            Model.consumeSolution consumeMod = new Model.consumeSolution();
            if (this.DgvConsumptionBill.Rows.Count > 0)
            {
                for (int i = 0; i < this.DgvConsumptionBill.Rows.Count; i++)
                {
                    if (DgvConsumptionBill.Rows[i].Cells["consumeType"].Value.ToString() != "")
                    {
                        consumeMod = consume.GetModel(int.Parse(DgvConsumptionBill.Rows[i].Cells["consumeType"].Value.ToString()));
                        DgvConsumptionBill.Rows[i].Cells["CardType"].Value = consumeMod.solutionName;
                    }
                    if (DgvConsumptionBill.Rows[i].Cells["Discount"].Value.ToString() != "")
                    {
                        DgvConsumptionBill.Rows[i].Cells["DiscountNew"].Value = DgvConsumptionBill.Rows[i].Cells["Discount"].Value + "%";
                    }
                }
            }
        }

        private void DgvConsumptionBill_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
           string ID=  DgvConsumptionBill.CurrentRow.Cells["Column1"].Value.ToString();
           goodsInfo goods = new goodsInfo();
           ZG_member.Model.goodsInfo goodsModel = new ZG_member.Model.goodsInfo();
           DataTable dt=  goods.GetListWhere(" wasteBookId='"+ID+"'").Tables[0];
           goods gd = new goods();
           ZG_member.Model.goods goodsMode = new ZG_member.Model.goods();
           dataGridView1.DataSource = dt;
           if (dataGridView1.Rows.Count != 0)
           {
               foreach (DataGridViewRow item in dataGridView1.Rows)
               {
                   if (item.Cells["gid"].Value != "")
                   {
                       goodsMode = gd.GetModelGoodsId(Convert.ToInt32(item.Cells["gid"].Value));
                       item.Cells["gidNew"].Value = goodsMode.goodsName;
                   }
               }
           }
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(((e.KeyChar >= '0') && (e.KeyChar <= '9')) || e.KeyChar <= 31))
            {
                //if (e.KeyChar == '.')
                //{
                //    if (((TextBox)sender).Text.Trim().IndexOf('.') > -1)
                //        e.Handled = true;
                //}
                //else
                e.Handled = true;
            }
            else
            {
                if (e.KeyChar <= 31)
                {
                    e.Handled = false;
                }
                else if (((TextBox)sender).Text.Trim().IndexOf('.') > -1)
                {
                    if (((TextBox)sender).Text.Trim().Substring(((TextBox)sender).Text.Trim().IndexOf('.') + 1).Length >= 4)
                        e.Handled = true;
                }
            }
        }

        private void TxtConsumer_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(((e.KeyChar >= '0') && (e.KeyChar <= '9')) || e.KeyChar <= 31))
            {
                //if (e.KeyChar == '.')
                //{
                //    if (((TextBox)sender).Text.Trim().IndexOf('.') > -1)
                //        e.Handled = true;
                //}
                //else
                e.Handled = true;
            }
            else
            {
                if (e.KeyChar <= 31)
                {
                    e.Handled = false;
                }
                else if (((TextBox)sender).Text.Trim().IndexOf('.') > -1)
                {
                    if (((TextBox)sender).Text.Trim().Substring(((TextBox)sender).Text.Trim().IndexOf('.') + 1).Length >= 4)
                        e.Handled = true;
                }
            }
        }

        private void 删除订单ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            wasteBook wb = new wasteBook();
            goodsInfo gi = new goodsInfo();
            goods g = new goods();
            memberInfo m = new memberInfo();
            DataSet ds = gi.GetListWhere(" wasteBookId = " + DgvConsumptionBill.CurrentRow.Cells["Column1"].Value.ToString().Trim());
            Model.memberInfo memod = m.GetModels(DgvConsumptionBill.CurrentRow.Cells["Column4"].Value.ToString());
            if (memod == null)
            {
                MessageBox.Show("修改失败，该会员以不存在！");
                return;
            }
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                Model.goods gmodle = g.getModelGoodsIdString(ds.Tables[0].Rows[i]["gid"].ToString());
                gmodle.amount = gmodle.amount + int.Parse(ds.Tables[0].Rows[i]["goodscount"].ToString());
                if (g.Update(gmodle))
                {
                    
                }   
            }
            if (gi.Deletewhere(" wasteBookId = " + DgvConsumptionBill.CurrentRow.Cells["Column1"].Value.ToString().Trim()))
            {
                if (wb.Delete(int.Parse(DgvConsumptionBill.CurrentRow.Cells["Column1"].Value.ToString().Trim())))
                {
                    memod.Balance = memod.Balance + decimal.Parse(DgvConsumptionBill.CurrentRow.Cells["Column8"].Value.ToString());
                    memod.point = memod.point - int.Parse(DgvConsumptionBill.CurrentRow.Cells["Column13"].Value.ToString());
                    memod.consume = memod.consume - decimal.Parse(DgvConsumptionBill.CurrentRow.Cells["Column8"].Value.ToString()) - decimal.Parse(DgvConsumptionBill.CurrentRow.Cells["Column9"].Value.ToString());
                    if (m.Update(memod))
                    {
                        MessageBox.Show("删除成功！");
                    }
                    DgvConsumptionBill.Rows.RemoveAt(DgvConsumptionBill.CurrentRow.Index);
                }
            }
        }

        private void 修改单价ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Dingdanxiugai d = new Dingdanxiugai(1,this);
            d.ShowDialog();
        }

        private void 修改商品ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.dataGridView1.Rows.Count==0)
            {
                MessageBox.Show("该订单没有购买商品！");
                return;
            }
            Dingdanxiugai d = new Dingdanxiugai(2, this);
            d.ShowDialog();
        }

        

 




   






       



    }
}
